package com.example.we_chat_video
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Call
import androidx.compose.material.icons.filled.Phone
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview as ComposePreview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.we_chat_video.ui.theme.We_chat_videoTheme
import com.example.we_chat_video.ui.theme.WeChatGreen
import androidx.compose.ui.layout.ContentScale
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import coil.compose.rememberAsyncImagePainter
import kotlinx.coroutines.delay
import android.Manifest
import android.content.pm.PackageManager
import androidx.camera.core.CameraSelector
import androidx.camera.core.Preview as CameraPreview
import androidx.compose.foundation.border
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat
import androidx.camera.lifecycle.ProcessCameraProvider
import com.google.common.util.concurrent.ListenableFuture
import kotlinx.coroutines.launch
import androidx.camera.view.PreviewView
import androidx.camera.core.Preview
import java.util.concurrent.Executor
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.IntOffset
import kotlin.math.roundToInt
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.foundation.layout.offset
import android.util.Log
import androidx.compose.runtime.key
import androidx.activity.result.contract.ActivityResultContracts.PickVisualMedia
import androidx.activity.result.contract.ActivityResultContracts.GetContent
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.TextField
import androidx.compose.runtime.MutableState
import android.view.ViewGroup
import androidx.compose.material.icons.filled.KeyboardArrowRight
import android.content.Context
import android.media.MediaPlayer
import androidx.compose.runtime.rememberCoroutineScope

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            We_chat_videoTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    AppNavigation()
                }
            }
        }
    }
}

@Composable
fun AppNavigation() {
    val navController = rememberNavController()
    val context = LocalContext.current
    val activity = (context as? ComponentActivity)

    // 添加退出应用的回调
    val exitToHome: () -> Unit = {
        activity?.finish()  // 直接结束当前Activity
    }
    
    // 在导航控制器级别保存媒体列表和其他状态
    val selectedMedia = remember { mutableStateListOf<Uri>() }
    val avatarUri = remember { mutableStateOf<Uri?>(null) }
    val nickname = remember { mutableStateOf("王明") }
    
    NavHost(navController = navController, startDestination = "home") {
        composable("home") {
            MainScreen(
                selectedMedia = selectedMedia,
                avatarUri = avatarUri,
                nickname = nickname,
                onStartClick = { navController.navigate("incoming") }
            )
        }
        composable("incoming") {
            CallIncomingScreen(
                avatarUri = avatarUri.value,
                nickname = nickname.value,
                onCallAccept = { navController.navigate("videocall") },
                onCallReject = exitToHome
            )
        }
        composable("videocall") {
            VideoCallScreen(
                mediaUris = selectedMedia,  // 使用共享的媒体列表而不是创建新的空列表
                onCallEnd = exitToHome
            )
        }
    }
}

@Composable
fun MainScreen(
    selectedMedia: MutableList<Uri>,
    avatarUri: MutableState<Uri?>,
    nickname: MutableState<String>,
    onStartClick: () -> Unit
) {
    val context = LocalContext.current
    
    var currentAvatarUri by avatarUri
    var currentNickname by nickname

    // 创建相册选择器启动器 - 允许选择多个照片和视频
    val mediaPickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.PickMultipleVisualMedia(maxItems = 10)
    ) { uris ->
        if (uris.isNotEmpty()) {
            selectedMedia.clear()
            selectedMedia.addAll(uris)
            Toast.makeText(context, "已选择 ${uris.size} 个文件", Toast.LENGTH_SHORT).show()
        }
    }

    // 创建头像选择器启动器
    val avatarPickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.PickVisualMedia()
    ) { uri ->
        currentAvatarUri = uri
        Toast.makeText(context, "头像已设置", Toast.LENGTH_SHORT).show()
    }

    // 新增设置昵称对话框状态
    var showNicknameDialog by remember { mutableStateOf(false) }

    // 新增设置昵称对话框
    if (showNicknameDialog) {
        AlertDialog(
            onDismissRequest = { showNicknameDialog = false },
            title = { Text("设置昵称") },
            text = {
                TextField(
                    value = currentNickname,
                    onValueChange = { currentNickname = it },
                    label = { Text("请输入昵称") }
                )
            },
            confirmButton = {
                Button(onClick = { showNicknameDialog = false }) {
                    Text("确定")
                }
            }
        )
    }

    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            Text(
                text = "微信视频通话模拟器",
                fontSize = 24.sp,
                fontWeight = FontWeight.Bold,
                color = WeChatGreen
            )
            
            Spacer(modifier = Modifier.height(48.dp))
            
            // 使用统一风格的按钮组
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                modifier = Modifier.fillMaxWidth()
            ) {
                // 选择视频按钮
                StylishButton(
                    onClick = { 
                        mediaPickerLauncher.launch(
                            PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageAndVideo)
                        )
                    },
                    icon = R.drawable.ic_video,
                    text = "选择视频/照片",
                    tint = WeChatGreen
                )
                
                Spacer(modifier = Modifier.height(16.dp))
                
                // 设置头像按钮
                StylishButton(
                    onClick = { 
                        avatarPickerLauncher.launch(
                            PickVisualMediaRequest(PickVisualMedia.ImageOnly)
                        )
                    },
                    icon = R.drawable.picture,
                    text = "设置头像",
                    tint = Color(0xFF5B86E5)
                )
                
                Spacer(modifier = Modifier.height(16.dp))
                
                // 设置昵称按钮
                StylishButton(
                    onClick = { showNicknameDialog = true },
                    icon = R.drawable.picture,
                    text = "设置昵称",
                    tint = Color(0xFF36D1DC)
                )
            }

            if (selectedMedia.isNotEmpty()) {
                Spacer(modifier = Modifier.height(24.dp))
                Text(
                    text = "已选择 ${selectedMedia.size} 个文件",
                    fontSize = 16.sp,
                    color = MaterialTheme.colorScheme.onBackground
                )
                
                Spacer(modifier = Modifier.height(24.dp))
                StartButton(
                    onClick = onStartClick
                )
            }
        }
    }
}

@Composable
fun VideoCallScreen(
    mediaUris: List<Uri>,
    onCallEnd: () -> Unit  // 现在这个回调会直接退出应用
) {
    val context = LocalContext.current
    val lifecycleOwner = LocalLifecycleOwner.current
    val density = LocalDensity.current.density
    
    // 跟踪当前播放的媒体索引
    var currentMediaIndex by remember { mutableIntStateOf(0) }
    // 跟踪当前显示的是视频还是照片
    var isCurrentVideo by remember { mutableStateOf(false) }
    // 麦克风状态
    var isMicOn by remember { mutableStateOf(true) }
    // 视频是否播放完成
    var isVideoPlaybackCompleted by remember { mutableStateOf(false) }
    // 摄像头权限状态
    var hasCameraPermission by remember { mutableStateOf(false) }
    // 添加摄像头小窗口的位置状态
    var cameraPositionOffset by remember { mutableStateOf(Offset(0f, 0f)) }
    // 添加一个状态来定期刷新小窗口
    var refreshCounter by remember { mutableIntStateOf(0) }
    var isActiveDragging by remember { mutableStateOf(false) }
    
    // 创建ExoPlayer实例
    val exoPlayer = remember {
        ExoPlayer.Builder(context).build().apply {
            repeatMode = Player.REPEAT_MODE_OFF  // 关闭单个媒体的循环
            playWhenReady = true
            
            addListener(object : Player.Listener {
                override fun onPlaybackStateChanged(playbackState: Int) {
                    if (playbackState == Player.STATE_ENDED) {
                        isVideoPlaybackCompleted = true
                    }
                }
            })
        }
    }
    
    // 请求摄像头权限
    val cameraPermissionLauncher = rememberLauncherForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        hasCameraPermission = isGranted
    }
    
    // 检查并请求权限
    LaunchedEffect(Unit) {
        try {
            // 确保相机资源被释放
            val cameraProvider = ProcessCameraProvider.getInstance(context).get()
            cameraProvider.unbindAll()
            // 给相机资源释放的时间
            delay(500)
            // 然后再检查和请求权限
            val permissionCheckResult = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
            if (permissionCheckResult == PackageManager.PERMISSION_GRANTED) {
                hasCameraPermission = true
            } else {
                cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
            }
        } catch (e: Exception) {
            Log.e("VideoCallScreen", "释放相机资源失败", e)
        }
    }
    
    // 监听生命周期，释放ExoPlayer资源
    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_PAUSE -> {
                    exoPlayer.pause()
                }
                Lifecycle.Event.ON_RESUME -> {
                    exoPlayer.play()
                }
                Lifecycle.Event.ON_DESTROY -> {
                    exoPlayer.release()
                }
                else -> {}
            }
        }
        lifecycleOwner.lifecycle.addObserver(observer)
        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
            exoPlayer.release()
        }
    }
    
    // 修改视频和图片切换逻辑
    LaunchedEffect(mediaUris, currentMediaIndex, isVideoPlaybackCompleted) {
        if (mediaUris.isNotEmpty()) {
            val mediaUri = mediaUris[currentMediaIndex]
            val mimeType = context.contentResolver.getType(mediaUri)
            
            isCurrentVideo = mimeType?.startsWith("video/") == true
            
            if (isCurrentVideo) {
                // 每次播放新视频时重置播放器
                exoPlayer.apply {
                    stop()
                    clearMediaItems()
                    setMediaItem(MediaItem.fromUri(mediaUri))
                    prepare()
                    play()
                    addListener(object : Player.Listener {
                        override fun onPlaybackStateChanged(state: Int) {
                            if (state == Player.STATE_ENDED) {
                                // 视频播放完成后自动切换到下一个
                                currentMediaIndex = (currentMediaIndex + 1) % mediaUris.size
                            }
                        }
                    })
                }
            } else {
                // 图片显示5秒后切换
                delay(5000)
                currentMediaIndex = (currentMediaIndex + 1) % mediaUris.size
            }
        }
    }
    
    // 使用优化的刷新策略
    LaunchedEffect(Unit) {
        // 仅在第一次加载时设置一次刷新计数器
        refreshCounter = 1
        // 移除周期性刷新，避免闪烁问题
        // 只保留拖动结束时的刷新机制
    }
    
    // 添加媒体播放器状态
    val mediaPlayer = remember { MediaPlayer() }
    var isSoundPlaying by remember { mutableStateOf(false) }

    // 初始化媒体播放器
    DisposableEffect(Unit) {
        try {
            val assetManager = context.assets
            mediaPlayer.apply {
                reset()
                setDataSource(assetManager.openFd("musics/over.mp3"))
                prepare()
            }
        } catch (e: Exception) {
            Log.e("VideoCallScreen", "音频加载失败", e)
        }

        onDispose {
            mediaPlayer.release()
        }
    }
    
    Box(modifier = Modifier.fillMaxSize()) {
        if (mediaUris.isNotEmpty()) {
            if (isCurrentVideo) {
                // 显示视频
                AndroidView(
                    factory = { ctx ->
                        androidx.media3.ui.PlayerView(ctx).apply {
                            player = exoPlayer
                            useController = false
                        }
                    },
                    modifier = Modifier.fillMaxSize()
                )
            } else {
                // 显示图片
                Image(
                    painter = rememberAsyncImagePainter(model = mediaUris[currentMediaIndex]),
                    contentDescription = "照片",
                    modifier = Modifier.fillMaxSize(),
                    contentScale = ContentScale.Crop
                )
            }
        }
        
        // 添加小窗口前置摄像头预览
        if (hasCameraPermission) {
            Box(
                modifier = Modifier
                    .offset(x = cameraPositionOffset.x.dp, y = cameraPositionOffset.y.dp)
                    .align(Alignment.TopEnd)
                    .padding(25.dp)
                    .size(width = 120.dp, height = 200.dp)
                    .clip(RoundedCornerShape(8.dp))
                    .background(Color.Black.copy(alpha = 0.2f))
                    .pointerInput(Unit) {
                        detectDragGestures(
                            onDragStart = { isActiveDragging = true },
                            onDragEnd = { 
                                isActiveDragging = false
                                // 拖动结束时触发一次刷新，但给予更长的延迟
                                kotlinx.coroutines.MainScope().launch {
                                    delay(300) // 增加延迟，确保UI稳定后再刷新
                                    refreshCounter = (refreshCounter + 1) % 1000
                                }
                            },
                            onDrag = { change, dragAmount ->
                                change.consume()
                                cameraPositionOffset = Offset(
                                    cameraPositionOffset.x + dragAmount.x / density,
                                    cameraPositionOffset.y + dragAmount.y / density
                                )
                            }
                        )
                    }
            ) {
                // 尝试使用FILL_START缩放类型，可能比FILL_CENTER更适合您的场景
                CameraPreview(
                    modifier = Modifier.fillMaxSize(),
                    scaleType = PreviewView.ScaleType.FILL_START
                )
            }
        }
        
        // 视频通话控制界面
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp),
            verticalArrangement = Arrangement.SpaceBetween
        ) {
            // 顶部信息栏
            Text(
                text = "",
                color = Color.White,
                fontSize = 16.sp,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.padding(8.dp)
            )
            
            // 底部控制按钮
            Column(
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                // 顶部功能按钮行 - 麦克风、扬声器、摄像头
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 30.dp),
                        horizontalArrangement = Arrangement.SpaceEvenly,
                        verticalAlignment = Alignment.CenterVertically
                ) {
                    // 麦克风按钮
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        var isMicOn by remember { mutableStateOf(true) }
                        IconButton(
                            onClick = { isMicOn = !isMicOn },
                            modifier = Modifier
                                .size(70.dp)
                                .clip(CircleShape)
                                .background(Color.White)
                        ) {
                            Icon(
                                painter = painterResource(id = R.drawable.ic_mic),
                                contentDescription = "麦克风",
                                tint = Color.Black,
                                modifier = Modifier.size(35.dp)
                            )
                        }
                        Spacer(modifier = Modifier.height(8.dp))
                        Text(
                            text = if (isMicOn) "麦克风已开" else "麦克风已关",
                            color = Color.White,
                            fontSize = 14.sp
                        )
                    }
                    
                    // 扬声器按钮
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        var isSpeakerOn by remember { mutableStateOf(true) }
                        IconButton(
                            onClick = { isSpeakerOn = !isSpeakerOn },
                            modifier = Modifier
                                .size(70.dp)
                                .clip(CircleShape)
                                .background(Color.White)
                        ) {
                            Icon(
                                painter = painterResource(id = R.drawable.ic_speaker),
                                contentDescription = "扬声器",
                                tint = Color.Black,
                                modifier = Modifier.size(35.dp)
                            )
                        }
                        Spacer(modifier = Modifier.height(8.dp))
                        Text(
                            text = if (isSpeakerOn) "扬声器已开" else "扬声器已关",
                            color = Color.White,
                            fontSize = 14.sp
                        )
                    }
                    
                    // 摄像头按钮
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Box(
                            modifier = Modifier
                                .size(70.dp)
                                .clip(CircleShape)
                                .background(Color.White),
                            contentAlignment = Alignment.Center
                        ) {
                            Icon(
                                painter = painterResource(id = R.drawable.camera),
                                contentDescription = "摄像头已开", 
                                tint = Color.Black,
                                modifier = Modifier.size(35.dp)
                            )
                        }
                        
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        Text(
                            text = "摄像头已开",
                            fontSize = 14.sp,
                            fontWeight = FontWeight.Normal,
                            color = Color.White
                        )
                    }
                }
                
                // 底部控制按钮行 - 添加左右两侧的图标
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 35.dp),
                        horizontalArrangement = Arrangement.SpaceEvenly,
                        verticalAlignment = Alignment.CenterVertically
                ) {
                    // 左侧的no图标 - 透明背景，显示原始颜色
                    IconButton(
                        onClick = { /* 处理no图标点击 */ },
                        modifier = Modifier
                            .size(50.dp)
                            .clip(CircleShape)
                            .background(Color.Transparent)
                    ) {
                        Icon(
                            painter = painterResource(id = R.drawable.no),
                            contentDescription = "拒绝",
                            tint = Color.Unspecified,
                            modifier = Modifier.size(30.dp)
                        )
                    }
                    
                    // 中间的结束通话按钮
                    FloatingActionButton(
                        onClick = {
                            // 播放结束音效
                            if (!isSoundPlaying) {
                                isSoundPlaying = true
                                try {
                                    mediaPlayer.seekTo(0)
                                    mediaPlayer.start()
                                    // 设置播放完成监听
                                    mediaPlayer.setOnCompletionListener {
                                        isSoundPlaying = false
                                        // 音效播放完成后执行原有操作
                                        onCallEnd()
                                    }
                                } catch (e: Exception) {
                                    Log.e("VideoCallScreen", "音频播放失败", e)
                                    onCallEnd()
                                }
                            }
                        },
                        containerColor = Color.Red,
                        contentColor = Color.White,
                        shape = CircleShape,
                        modifier = Modifier.size(75.dp)
                    ) {
                        Icon(
                            painter = painterResource(id = R.drawable.ic_call_end),
                            contentDescription = "结束通话",
                            modifier = Modifier.size(39.dp)
                        )
                    }
                    
                    // 右侧的reverse图标 - 透明背景，显示原始颜色
                    IconButton(
                        onClick = { /* 处理reverse图标点击 */ },
                        modifier = Modifier
                            .size(53.dp)
                            .clip(CircleShape)
                            .background(Color.Transparent)
                    ) {
                        Icon(
                            painter = painterResource(id = R.drawable.reverse),
                            contentDescription = "反转",
                            tint = Color.Unspecified,
                            modifier = Modifier.size(32.dp)
                        )
                    }
                }
            }
        }
    }
}

@Composable
fun CustomSwitchUserIcon(
    modifier: Modifier = Modifier,
    iconColor: Color = Color.White
) {
    Canvas(modifier = modifier.size(28.dp)) {
        // 绘制圆角矩形背景框（透明）
        drawRoundRect(
            color = Color.Transparent,
            cornerRadius = androidx.compose.ui.geometry.CornerRadius(8.dp.toPx(), 8.dp.toPx()),
            style = Stroke(width = 2.dp.toPx())
        )
        
        // 绘制人物剪影
        drawRect(
            color = iconColor,
            topLeft = Offset(center.x - 8.dp.toPx(), center.y - 4.dp.toPx()),
            size = Size(16.dp.toPx(), 8.dp.toPx())
        )
        drawCircle(
            color = iconColor,
            radius = 6.dp.toPx(),
            center = Offset(center.x, center.y - 10.dp.toPx())
        )
        
        // 绘制从右上角到左下角的斜线
        drawLine(
            color = iconColor,
            start = Offset(size.width - 4.dp.toPx(), 4.dp.toPx()),
            end = Offset(4.dp.toPx(), size.height - 4.dp.toPx()),
            strokeWidth = 2.dp.toPx(),
            cap = StrokeCap.Round
        )
    }
}

@Composable
fun StylishButton(
    onClick: () -> Unit,
    icon: Int,
    text: String,
    tint: Color
) {
    Button(
        onClick = onClick,
        shape = RoundedCornerShape(16.dp),
        colors = ButtonDefaults.buttonColors(
            containerColor = Color.White
        ),
        elevation = ButtonDefaults.buttonElevation(
            defaultElevation = 2.dp,
            pressedElevation = 4.dp
        ),
        modifier = Modifier
            .fillMaxWidth(0.8f)
            .height(68.dp)
            .border(
                width = 1.dp,
                color = Color(0xFFEEEEEE),
                shape = RoundedCornerShape(16.dp)
            )
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.Start,
            modifier = Modifier.fillMaxWidth()
        ) {
            // 图标容器
            Box(
                modifier = Modifier
                    .size(48.dp)
                    .clip(CircleShape)
                    .background(tint.copy(alpha = 0.1f)),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    painter = painterResource(id = icon),
                    contentDescription = text,
                    tint = tint,
                    modifier = Modifier.size(28.dp)
                )
            }
            
            Spacer(modifier = Modifier.width(16.dp))
            
            // 文本和箭头
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.Start,
                modifier = Modifier.fillMaxWidth()
            ) {
                Text(
                    text = text,
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Medium,
                    color = Color.DarkGray
                )
            }
        }
    }
}

@Composable
fun StartButton(onClick: () -> Unit) {
    Button(
        onClick = onClick,
        shape = RoundedCornerShape(28.dp),
        colors = ButtonDefaults.buttonColors(
            containerColor = WeChatGreen
        ),
        elevation = ButtonDefaults.buttonElevation(
            defaultElevation = 2.dp,
            pressedElevation = 4.dp
        ),
        modifier = Modifier
            .width(180.dp)
            .height(56.dp)
    ) {
        Icon(
            painter = painterResource(id = R.drawable.ic_video),
            contentDescription = "开始",
            tint = Color.White,
            modifier = Modifier.size(24.dp)
        )
        
        Spacer(modifier = Modifier.width(8.dp))
        
        Text(
            text = "开始通话",
            fontSize = 18.sp,
            fontWeight = FontWeight.Bold,
            color = Color.White,
        )
    }
}

@ComposePreview(showBackground = true)
@Composable
fun MainScreenPreview() {
    We_chat_videoTheme {
        MainScreen(mutableListOf(), mutableStateOf(null), mutableStateOf("王明"), {})
    }
}

// 优化CameraPreview函数，减少卡顿和闪烁
@Composable
fun CameraPreview(
    modifier: Modifier = Modifier,
    refreshKey: Int = 0, // 刷新键参数
    isIncomingScreen: Boolean = false,
    scaleType: PreviewView.ScaleType = PreviewView.ScaleType.FILL_CENTER // 添加缩放模式参数
) {
    val context = LocalContext.current
    val lifecycleOwner = LocalLifecycleOwner.current
    
    // 创建PreviewView - 使用COMPATIBLE模式而非PERFORMANCE提高稳定性
    val previewView = remember { 
        PreviewView(context).apply {
            // 使用COMPATIBLE模式提高稳定性
            implementationMode = PreviewView.ImplementationMode.COMPATIBLE
            // 确保应用传入的缩放类型
            this.scaleType = scaleType
            // 添加强制裁剪设置
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
        }
    }
    
    var isCameraBound by remember { mutableStateOf(false) }
    var isRefreshing by remember { mutableStateOf(false) }
    
    // 创建CameraX相关变量
    val cameraProviderFuture = remember { ProcessCameraProvider.getInstance(context) }
    val executor = remember { ContextCompat.getMainExecutor(context) }
    val cameraExecutor = remember { Executors.newSingleThreadExecutor() }
    
    // 完全移除定期刷新触发器，只在必要时刷新
    
    // 仅在初始化时绑定相机，避免频繁重新绑定
    LaunchedEffect(Unit) {
        if (!isRefreshing && !isCameraBound) {
            isRefreshing = true
            Log.d("CameraPreview", "初始化相机预览")
            
            try {
                // 增加延迟，确保之前的相机操作完成
                delay(300) // 增加延迟时间，等待相机资源完全释放
                
                val listener = Runnable {
                    try {
                        val cameraProvider = cameraProviderFuture.get()
                        
                        // 配置相机预览
                        val preview = Preview.Builder()
                            .setTargetRotation(previewView.display.rotation)
                            .build()
                            .also {
                                it.setSurfaceProvider(previewView.surfaceProvider)
                            }
                        
                        // 选择前置摄像头
                        val cameraSelector = CameraSelector.Builder()
                            .requireLensFacing(CameraSelector.LENS_FACING_FRONT)
                            .build()
                        
                        // 释放所有之前的绑定
                        cameraProvider.unbindAll()
                        
                        try {
                            // 绑定用例到生命周期
                            cameraProvider.bindToLifecycle(
                                lifecycleOwner,
                                cameraSelector,
                                preview
                            )
                            
                            // 更新绑定状态
                            isCameraBound = true
                            Log.d("CameraPreview", "相机初始化成功")
                        } catch (e: Exception) {
                            Log.e("CameraPreview", "相机绑定失败", e)
                        }
                        
                    } catch (e: Exception) {
                        Log.e("CameraPreview", "相机初始化失败", e)
                    } finally {
                        isRefreshing = false
                    }
                }
                
                cameraProviderFuture.addListener(listener, executor)
            } catch (e: Exception) {
                isRefreshing = false
                Log.e("CameraPreview", "初始化相机失败", e)
            }
        }
    }
    
    // 当组件离开组合时清理资源
    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_RESUME -> {
                    // 当恢复时重新绑定相机
                    if (!isCameraBound && !isRefreshing) {
                        // 使用协程延迟执行相机绑定
                        kotlinx.coroutines.MainScope().launch {
                            delay(300) // 添加延迟
                            // 添加相机绑定逻辑
                            try {
                                val cameraProvider = cameraProviderFuture.get()
                                
                                val preview = Preview.Builder()
                                    .setTargetRotation(previewView.display.rotation)
                                    .build()
                                    .also {
                                        it.setSurfaceProvider(previewView.surfaceProvider)
                                    }
                                
                                val cameraSelector = CameraSelector.Builder()
                                    .requireLensFacing(CameraSelector.LENS_FACING_FRONT)
                                    .build()
                                
                                cameraProvider.unbindAll()
                                cameraProvider.bindToLifecycle(
                                    lifecycleOwner,
                                    cameraSelector,
                                    preview
                                )
                                
                                isCameraBound = true
                            } catch (e: Exception) {
                                Log.e("CameraPreview", "恢复时相机绑定失败", e)
                            }
                        }
                    }
                }
                Lifecycle.Event.ON_PAUSE -> {
                    try {
                        val cameraProvider = cameraProviderFuture.get()
                        cameraProvider.unbindAll()
                        isCameraBound = false
                    } catch (e: Exception) {
                        Log.e("CameraPreview", "暂停时解绑相机失败", e)
                    }
                }
                else -> {}
            }
        }
        
        lifecycleOwner.lifecycle.addObserver(observer)
        
        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
            Log.d("CameraPreview", "清理相机资源")
            isCameraBound = false
            cameraExecutor.shutdown()
            try {
                val cameraProvider = cameraProviderFuture.get()
                cameraProvider.unbindAll()
            } catch (e: Exception) {
                Log.e("CameraPreview", "清理相机资源失败", e)
            }
        }
    }
    
    // 渲染摄像头预览视图
    AndroidView(
        factory = { previewView },
        modifier = modifier,
        update = { /* 不在更新回调中执行任何逻辑 */ }
    )
}

@Composable
fun CallIncomingScreen(
    avatarUri: Uri?,
    nickname: String,
    onCallAccept: () -> Unit,
    onCallReject: () -> Unit
) {
    val context = LocalContext.current
    val lifecycleOwner = LocalLifecycleOwner.current
    val coroutineScope = rememberCoroutineScope()
    
    // 使用更安全的方式创建和管理 MediaPlayer
    var dialingSound: MediaPlayer? = null
    var callEndSound: MediaPlayer? = null
    
    try {
        // 创建铃声播放器
        dialingSound = MediaPlayer()
        
        // 检查文件是否存在并加载
        val assetManager = context.assets
        val fileList = assetManager.list("musics") ?: emptyArray()
        
        if (fileList.contains("ding.mp3")) {
            try {
                assetManager.openFd("musics/ding.mp3").use { afd ->
                    dialingSound.setDataSource(afd.fileDescriptor, afd.startOffset, afd.length)
                    dialingSound.prepare()
                    dialingSound.isLooping = true
                }
            } catch (e: Exception) {
                Log.e("CallScreen", "铃声音频加载失败", e)
                dialingSound.release()
                dialingSound = null
            }
        } else {
            Log.e("CallScreen", "找不到铃声文件 musics/ding.mp3")
            dialingSound.release()
            dialingSound = null
        }
        
        // 创建通话结束音效播放器
        if (fileList.contains("over.mp3")) {
            callEndSound = MediaPlayer()
            try {
                assetManager.openFd("musics/over.mp3").use { afd ->
                    callEndSound.setDataSource(afd.fileDescriptor, afd.startOffset, afd.length)
                    callEndSound.prepare()
                }
            } catch (e: Exception) {
                Log.e("CallScreen", "结束音频加载失败", e)
                callEndSound.release()
                callEndSound = null
            }
        } else {
            Log.e("CallScreen", "找不到结束音频文件 musics/over.mp3")
        }
    } catch (e: Exception) {
        Log.e("CallScreen", "MediaPlayer初始化失败", e)
        dialingSound?.release()
        callEndSound?.release()
        dialingSound = null
        callEndSound = null
    }
    
    // 状态变量，防止重复释放资源
    var mediaPlayersReleased by remember { mutableStateOf(false) }
    
    // 开始播放来电铃声
    LaunchedEffect(Unit) {
        try {
            dialingSound?.start()
        } catch (e: Exception) {
            Log.e("CallScreen", "铃声播放失败", e)
        }
    }
    
    // 包装处理函数，增加安全处理
    val handleCallAccept = {
        if (!mediaPlayersReleased) {
            try {
                // 停止铃声
                if (dialingSound?.isPlaying == true) {
                    dialingSound.stop()
                }
                
                // 播放结束音效
                callEndSound?.let { player ->
                    try {
                        player.start()
                    } catch (e: Exception) {
                        Log.e("CallScreen", "结束音效播放失败", e)
                    }
                }
                
                // 延迟释放资源，确保音效播放完成
                coroutineScope.launch {
                    delay(1000) // 等待1秒确保音效有机会播放
                    try {
                        dialingSound?.release()
                        callEndSound?.release()
                        mediaPlayersReleased = true
                    } catch (e: Exception) {
                        Log.e("CallScreen", "MediaPlayer资源释放失败", e)
                    }
                }
            } catch (e: Exception) {
                Log.e("CallScreen", "接听处理时出错", e)
            }
        }
        onCallAccept()
    }
    
    val handleCallReject = {
        if (!mediaPlayersReleased) {
            try {
                // 停止铃声
                if (dialingSound?.isPlaying == true) {
                    dialingSound.stop()
                }
                
                // 播放结束音效
                callEndSound?.let { player ->
                    try {
                        player.start()
                    } catch (e: Exception) {
                        Log.e("CallScreen", "结束音效播放失败", e)
                    }
                }
                
                // 延迟释放资源，确保音效播放完成
                coroutineScope.launch {
                    delay(1000) // 等待1秒确保音效有机会播放
                    try {
                        dialingSound?.release()
                        callEndSound?.release()
                        mediaPlayersReleased = true
                    } catch (e: Exception) {
                        Log.e("CallScreen", "MediaPlayer资源释放失败", e)
                    }
                }
            } catch (e: Exception) {
                Log.e("CallScreen", "拒绝处理时出错", e)
            }
        }
        onCallReject()
    }
    
    // 组件销毁时清理资源
    DisposableEffect(lifecycleOwner) {
        onDispose {
            if (!mediaPlayersReleased) {
                try {
                    dialingSound?.apply {
                        if (isPlaying) stop()
                        release()
                    }
                    callEndSound?.apply {
                        if (isPlaying) stop()
                        release()
                    }
                    mediaPlayersReleased = true
                } catch (e: Exception) {
                    Log.e("CallScreen", "清理MediaPlayer资源失败", e)
                }
            }
        }
    }
    
    // 摄像头权限状态
    var hasCameraPermission by remember { mutableStateOf(false) }
    
    // 请求摄像头权限
    val cameraPermissionLauncher = rememberLauncherForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        hasCameraPermission = isGranted
    }
    
    // 检查并请求权限
    LaunchedEffect(Unit) {
        val permissionCheckResult = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
        if (permissionCheckResult == PackageManager.PERMISSION_GRANTED) {
            hasCameraPermission = true
        } else {
            cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
        }
    }
    
    var cameraProvider: ProcessCameraProvider? = null
    
    Box(modifier = Modifier.fillMaxSize()) {
        // 显示前置摄像头画面作为背景
        if (hasCameraPermission) {
            // 添加key使组件唯一标识为"incoming_preview"
            key("incoming_preview") {
                CameraPreview(
                    modifier = Modifier.fillMaxSize(),
                    isIncomingScreen = true // 添加标识，表明是来电界面
                )
            }
        } else {
            // 如果没有权限显示黑色背景
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(Color.Black)
            )
        }
        
        // 修改来电界面的UI布局，调整文本位置
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp),
            verticalArrangement = Arrangement.SpaceBetween,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 顶部显示来电信息
            Column(
                modifier = Modifier.padding(top = 150.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                // 显示头像
                Box(
                    modifier = Modifier
                        .size(65.dp) // 设置容器大小
                        .clip(RoundedCornerShape(10.dp)) // 设置圆角
                        .background(Color.Gray) // 可选：设置背景颜色
                ) {
                    Image(
                        painter = if (avatarUri != null) {
                            rememberAsyncImagePainter(model = avatarUri)
                        } else {
                            painterResource(id = R.drawable.picture)
                        },
                        contentDescription = "头像",
                        modifier = Modifier.fillMaxSize(), // 使头像填满容器
                        contentScale = ContentScale.Crop // 添加这一行确保图像充满容器
                    )
                }
                
                Spacer(modifier = Modifier.height(8.dp))
                
                Text(
                    text = nickname.ifEmpty { "王明" },
                    fontSize = 22.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color.White
                )
            }
            
            // 增加一个空间，将三个功能按钮往下移
            Spacer(modifier = Modifier.weight(0.3f))
            
            // 在中间功能按钮上方显示"邀请你视频通话..."文本
            Text(
                text = "邀请你视频通话...",
                fontSize = 18.sp,
                color = Color.White,
                modifier = Modifier.padding(bottom = 24.dp)
            )
            
            // 中间的功能按钮
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 20.dp),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                // 翻转按钮 - 使用原始图标颜色
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Box(
                        modifier = Modifier
                            .size(72.dp)
                            .clip(CircleShape)
                            .background(Color(0xCC444444)),  // 深灰色背景
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            painter = painterResource(id = R.drawable.reverse),
                            contentDescription = "翻转",
                            tint = Color.Unspecified,  // 不应用tint，显示原始图片颜色
                            modifier = Modifier.size(32.dp)
                        )
                    }
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    Text(
                        text = "翻转",
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Normal,
                        color = Color.White
                    )
                }
                
                // 模糊背景按钮 (保持不变)
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Box(
                        modifier = Modifier
                            .size(72.dp)  // 调整大小与其他按钮一致
                            .clip(CircleShape)
                            .background(Color(0xCC444444)),  // 匹配其他按钮的背景
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            painter = painterResource(id = R.drawable.no),
                            contentDescription = "模糊背景",
                            tint = Color.White,
                            modifier = Modifier.size(32.dp)
                        )
                    }
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    Text(
                        text = "模糊背景",
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Normal,
                        color = Color.White
                    )
                }
                
                // 摄像头已开按钮 - 更接近原始设计
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Box(
                        modifier = Modifier
                            .size(72.dp)
                            .clip(CircleShape)
                            .background(Color.White),
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            painter = painterResource(id = R.drawable.camera),
                            contentDescription = "摄像头已开",
                            tint = Color.Black,
                            modifier = Modifier.size(45.dp)
                        )
                    }
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    Text(
                        text = "摄像头已开",
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Normal,
                        color = Color.White
                    )
                }
            }
            
            // 底部显示接听和拒绝按钮
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 35.dp, start = 30.dp, end = 20.dp),  // 增加左右边距，使按钮靠近屏幕边缘
                horizontalArrangement = Arrangement.SpaceBetween,  // 改为SpaceBetween，使按钮分布在两侧
            ) {
                // 拒绝按钮 - 红色
                FloatingActionButton(
                    onClick = {
                        handleCallReject()
                        onCallReject()  // 直接调用退出回调
                    },
                    containerColor = Color.Red,
                    contentColor = Color.White,
                    shape = CircleShape,
                    modifier = Modifier.size(75.dp)
                ) {
                    Icon(
                        painter = painterResource(id = R.drawable.ic_call_end),
                        contentDescription = "拒绝",
                        modifier = Modifier.size(36.dp)
                    )
                }
                
                // 接听按钮 - 绿色
                FloatingActionButton(
                    onClick = handleCallAccept,  // 使用新的处理函数
                    containerColor = WeChatGreen,
                    contentColor = Color.White,
                    shape = CircleShape,
                    modifier = Modifier.size(75.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Phone,
                        contentDescription = "接听",
                        modifier = Modifier.size(36.dp)
                    )
                }
            }
        }
    }
}